<template>
  <ElForm
    style="display: inline-block; width: 100%"
    :inline="true"
    ref="Mikeform"
    @submit.prevent
    :model="formFields"
    :label-width="labelWidth"
  >
    <template v-for="(row, findex) in formRules" :key="findex">
      <div class="form-item">
        <ElFormItem
          :label="item.type == 'divider' ? '' : item.title ? item.title + '：' : ''"
          v-for="(item, index) in row"
          :prop="item.field"
          :key="item.field + index"
          :style="{
            width:
              item.colSize == 12 || item.type == 'webEditor' || item.type == 'editor'
                ? '100'
                : item.colSize == 4
                ? '33.33%'
                : '50' + '%',
          }"
          :rules="{
            required: item.required,
            message: item.placeholder ? item.placeholder : item.title,
            trigger: item.type == 'text' ? 'blur' : 'change',
          }"
        >
          <ElInput
            v-if="item.type == 'text'"
            v-model="formFields[item.field]"
            :placeholder="item.placeholder ? item.placeholder : item.title"
            :disabled="item.readonly || item.disabled"
            v-show="!item.hidden"
            @click="item.onclick"
          />
          <ElSelect
            v-else-if="item.type == 'select'"
            v-model="formFields[item.field]"
            style="width: 100%"
            filterable
            :placeholder="item.placeholder ? item.placeholder : item.title"
            :multiple="item.multiple"
            :collapse-tags="item.collapseTags"
            :disabled="item.readonly || item.disabled"
            v-show="!item.hidden"
            @change="item.onChange"
          >
            <ElOption
              v-for="items in item.data"
              :key="items[item.dataKey]"
              :label="items[item.dataName]"
              :value="items[item.dataKey]"
            />
          </ElSelect>
          <ElSelectV2
            v-else-if="item.type == 'selectv2'"
            v-model="formFields[item.field]"
            style="width: 100%"
            :placeholder="item.placeholder ? item.placeholder : item.title"
            filterable
            @change="item.onChange"
            :options="item.data"
            :disabled="item.readonly || item.disabled"
            v-show="!item.hidden"
          />
          <ElDatePicker
            :disabled="item.readonly || item.disabled"
            v-show="!item.hidden"
            v-model="formFields[item.field]"
            type="datetime"
            :placeholder="item.placeholder"
            style="width: 100%"
            :format="item.format"
            :value-format="item.format"
            v-else-if="item.type == 'dateTime' && !item.isdisabledDate"
          />
          <ElDatePicker
            :disabled="item.readonly || item.disabled"
            v-show="!item.hidden"
            v-model="formFields[item.field]"
            type="datetime"
            :placeholder="item.placeholder"
            style="width: 100%"
            :format="item.format"
            :value-format="item.format"
            v-else-if="item.type == 'dateTime' && item.isdisabledDate"
            :disabled-date="disableDate"
            :disabled-hours="disabledHour"
            :disabled-minutes="disabledMinute"
            :disabled-seconds="disabledSecond"
          />
          <ElDatePicker
            :disabled="item.readonly || item.disabled"
            v-show="!item.hidden"
            v-model="formFields[item.field]"
            type="date"
            :placeholder="item.placeholder"
            style="width: 100%"
            :format="item.format"
            :value-format="item.format"
            v-else-if="item.type == 'date'"
          />
          <div v-else-if="item.type == 'editor'">
            <RichTextEditor :value="formFields[item.field]" @update:value="handleUpdateValue" />
          </div>
          <div v-else-if="item.type == 'radio'" class="hint">
            <ElRadioGroup
              :disabled="item.readonly || item.disabled"
              v-show="!item.hidden"
              v-model="formFields[item.field]"
              v-if="item.type == 'radio'"
              @change="item.onChange"
            >
              <ElRadio
                v-for="items in item.data"
                :disabled="item.readonly || item.disabled"
                :key="items[item.dataKey]"
                :label="items[item.dataKey]"
              >
                {{ items[item.dataName] }}
              </ElRadio>
            </ElRadioGroup>
            <!-- 格外添加 -->
            <span v-if="item.field == 'unitStatus'" style="color: red"
              >没有数据操作，选用组合可以提升加载速度</span
            >
            <!-- <ElButton
              type="primary"
              @click="handleClickDiolog"
              v-if="item.field == 'unitRight' && formFields[item.field] == '1'"
              >单元权限</ElButton
            > -->
          </div>
          <div v-else-if="item.type == 'checkbox'">
            <template v-if="item.group">
              <ElCheckboxGroup
                @change="item.onChange"
                v-model="formFields[item.field]"
                :disabled="item.readonly || item.disabled"
              >
                <ElCheckbox
                  v-for="items in item.data"
                  :key="items[item.dataKey]"
                  :label="items[item.dataKey]"
                >
                  {{ items[item.dataName] }}</ElCheckbox
                >
              </ElCheckboxGroup>
            </template>
            <template v-else>
              <ElCheckbox
                :disabled="item.readonly || item.disabled"
                v-for="items in item.data"
                v-model="formFields[item.field]"
                :key="items[item.dataKey]"
                :label="items[item.dataKey]"
                :true-label="items[item.dataKey]"
                @change="item.onChange"
                >{{ items[item.dataName] }}</ElCheckbox
              >
            </template>
          </div>
          <ElInput
            clearable
            style="width: 100%"
            :disabled="item.readonly || item.disabled"
            v-else-if="item.type == 'textarea'"
            v-model="formFields[item.field]"
            @click="item.onClick"
            type="textarea"
            :autosize="{
              minRows: !item.minRows ? 2 : item.minRows,
              maxRows: !item.maxRows ? 10 : item.maxRows,
            }"
            :placeholder="item.placeholder ? item.placeholder : item.title"
          />
          <template v-else-if="item.type == 'password'">
            <ElInput
              :disabled="item.readonly || item.disabled"
              v-model="formFields[item.field]"
              type="password"
              show-password
            />
          </template>
          <template v-else-if="item.type == 'divider'">
            <ElDivider :border-style="item.borderStyle" :content-position="item.contenPposition">
              <span
                v-html="item.title"
                :style="{ fontSize: item.fontSize, color: item.fontSziecolor }"
              ></span>
            </ElDivider>
          </template>
          <template v-else-if="item.type == 'switch'">
            <ElSwitch
              :disabled="item.readonly || item.disabled"
              inline-prompt
              v-model="formFields[item.field]"
              :active-value="item.activeValue"
              :inactive-value="item.inactiveValue"
            />
          </template>
          <template v-else-if="item.type == 'upload'">
            <ElUpload
              v-if="!item.readonly"
              ref="upload"
              class="upload-demo"
              :action="item.action"
              :limit="item.limit"
              :file-list="formFields[item.field]"
              :on-remove="(response, field) => fileRemove(response, item.field)"
              :on-preview="handleDownload"
              :on-success="(response, file, field) => fileSuccess(response, file, item.field)"
            >
              <template #trigger>
                <ElButton
                  :style="{ background: item.background, borderColor: item.background }"
                  type="primary"
                  >文件上传</ElButton
                >
              </template>
            </ElUpload>
            <ElUpload
              v-else
              ref="upload"
              class="upload-demo"
              :action="item.action"
              :limit="item.limit"
              :disabled="item.readonly"
              :file-list="formFields[item.field]"
              :on-preview="handleDownload"
            />
          </template>
          <template v-else-if="item.type == 'upload2'">
            <ElUpload
              ref="upload"
              class="upload-demo"
              :auto-upload="false"
              :file-list="formFields[item.field]"
              :limit="1"
              @change="changeFile"
              :on-remove="(response, field) => fileRemove2()"
            >
              <template #trigger>
                <ElButton
                  :style="{ background: item.background, borderColor: item.background }"
                  type="primary"
                  >文件上传</ElButton
                >
              </template>
            </ElUpload>
          </template>

          <template v-else-if="item.type == 'webEditor' && !item.switch">
            <WebEditor
              v-model="formFields[item.field]"
              :language="item.language"
              width="100%"
              height="115px"
            />
          </template>
          <template
            v-else-if="item.type == 'webEditor' && item.switch && formFields['dataStatus'] == 1"
          >
            <WebEditor
              v-model="formFields[item.field]"
              :language="item.language"
              width="100%"
              height="115px"
            />
          </template>
          <template
            v-else-if="item.type == 'webEditor' && item.switch && formFields['dataStatus'] == 0"
          >
            <ElInput
              v-model="formFields[item.field]"
              :disabled="item.readonly || item.disabled"
              v-show="!item.hidden"
              @click="item.onclick"
              :placeholder="item.placeholder ? item.placeholder : item.title"
            />
          </template>
        </ElFormItem>
      </div>
    </template>
    <slot></slot>
    <div style="width: 100%; text-align: center">
      <slot name="footer"></slot>
    </div>
  </ElForm>
</template>

<script setup lang="ts">
  import { exportFile } from '@/utils/exportFile';
  import { fileDelete } from '@/api/publicApi';
  import type { UploadFile } from 'element-plus';
  // import { unitPermissionsRight } from '@/pages/lowcodePower/views/lowCode/components/rightLowCode/index';
  const emit = defineEmits<Emits>();
  interface Emits {
    (e: 'update:value', val: Object): void;
    (e: 'update:valueEditor', val: string): void;
  }
  const success = ref<Boolean>(true);
  const Mikeform = ref<any>(null);
  const formFields = ref<Object>({});
  const formRules = ref<any[]>([]);
  const props = defineProps({
    loadKey: {
      // 是否加载formRules字段配置的数据源
      type: Boolean,
      default: true,
    },
    width: {
      // 表单宽度
      type: Number,
      default: 0,
    },
    labelWidth: {
      // 表单左边label文字标签的宽度
      type: Number,
      default: 100,
    },
    formRules: {
      // 表单配置规则，如字段类型，是否必填
      type: Array<any[]>,
      default: () => [],
    },
    formFields: {
      type: Object as any,
      default: () => {
        return {};
      },
    },
    size: {
      type: String, //large / default / small
      default: 'large',
    },
    select2Count: {
      //超出数量显示select2组件 留着 让用户填写还是内部判断组件
      type: Number,
      default: 500,
    },
  });
  onMounted(() => {
    // formFields.value = props.formFields;
    // formRules.value = props.formRules;
    // console.log('formRules.value', formRules.value);
  });

  watch(
    props,
    async (value) => {
      formFields.value = value.formFields;
      formRules.value = value.formRules;
    },
    {
      deep: true,
      immediate: true,
    },
  );
  /* 限制天 */
  const disableDate = (time) => {
    return time.getTime() < Date.now() - 8.64e7;
  };

  /* 限制小时 */
  const disabledHour = () => {
    const arrs = [] as number[];
    for (let i = 0; i < 24; i++) {
      if (new Date().getHours() <= i) continue;
      arrs.push(i);
    }
    return arrs;
  };

  /* 限制分 */
  const disabledMinute = () => {
    const arrs = [] as number[];
    for (let i = 0; i < 60; i++) {
      if (new Date().getMinutes() <= i) continue;
      arrs.push(i);
    }
    return arrs;
  };

  /* 限制秒 */
  const disabledSecond = () => {
    const arrs = [] as number[];
    for (let i = 0; i < 60; i++) {
      if (new Date().getSeconds() <= i) continue;
      arrs.push(i);
    }
    return arrs;
  };
  const validate = () => {
    Mikeform.value.validate((valid) => {
      if (valid) {
        success.value = true;
        emit('update:value', formFields.value);
      } else {
        success.value = false;
      }
    });
  };
  const reset = () => {
    Mikeform.value.resetFields();
  };
  // // 格外添加
  // const handleClickDiolog = () => {
  //   unitPermissionsRight.value = true;
  // };
  const fileRemove = async (fileList: any, field) => {
    if (fileList.id) {
      await fileDelete(fileList.id);
      for (let i = 0; i < formFields.value[field].length; i++) {
        if (formFields.value[field][i].id === fileList.id) {
          formFields.value[field].splice(i, 1);
        }
      }
    } else {
      await fileDelete(fileList.response.data.id);
      for (let i = 0; i < formFields.value[field].length; i++) {
        if (formFields.value[field][i].id === fileList.response.data.id) {
          formFields.value[field].splice(i, 1);
        }
      }
    }
  };

  const fileSuccess = (value, list, field: string) => {
    if (value.code == 0) {
      if (!formFields.value[field]) {
        let data = [] as any;
        data.push({
          id: value.data.id,
          name: value.data.filename,
          url: `/sys/file/getfile/${value.data.id}`,
          uid: list.uid,
          status: list.status,
        });
        formFields.value[field] = data;
      } else {
        formFields.value[field].push({
          id: value.data.id,
          name: value.data.filename,
          url: `/sys/file/getfile/${value.data.id}`,
          uid: list.uid,
          status: list.status,
        });
      }
      ElMessage.success('上传成功');
    } else {
      ElMessage.error('上传失败');
    }
  };
  const handleDownload = async (file: any) => {
    if (file.id) {
      exportFile(file.url, file.name);
    } else {
      ElMessage.info('暂无下载路径');
    }
  };
  const handleUpdateValue = (value: string) => {
    emit('update:valueEditor', value);
  };
  const file = ref<UploadFile>();
  const changeFile = (UploadFile: UploadFile) => {
    file.value = UploadFile;
  };
  // 获取文件
  const getFile = () => {
    return file;
  };

  const fileRemove2 = async () => {
    file.value = undefined;
  };

  defineExpose({
    reset,
    validate,
    success,
    getFile,
    fileRemove2,
  });
</script>

<style lang="scss" scoped>
  .form-item {
    width: $width;
    :deep(.el-form-item) {
      margin-right: 0;
    }
  }
  .form-item_textarea {
    width: $width;
    justify-content: flex-end;
    display: flex;
    :deep(.el-form-item) {
      width: $width;
    }
  }
  :deep(.el-radio-group) {
    width: $width;
    flex: 1;
  }
  .hint {
    width: $width;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  :deep(.el-form-item) {
    width: $width;
  }
  :deep(.el-input__wrapper) {
    width: $width;
    box-sizing: border-box;
  }
  :deep(.el-form-item__content) {
    > div {
      width: $width;
    }
  }
  :deep(.el-upload-list) {
    margin: 0;
  }
</style>
